package gotnames.web.st;

import gotnames.Utils;
import gotnames.dm.KTrans;
import gotnames.dm.ProfilePicture;
import gotnames.dm.ProfilePictureData;
import gotnames.dm.QueryBuilder;
import gotnames.dm.User;
import gotnames.dm.User.Gender;
import gotnames.web.GotNamesServlet.UserAuthenticator;

import java.util.List;

import javax.jdo.PersistenceManager;

import com.medallia.spider.DropdownElement;

/**
 * Task which both renders and receives a form users can use to edit their
 * information.
 */
public class EditProfileTask extends GotNamesTask {
	
	@Input interface Params {
		String email();
		String firstName();
		String lastName();
		Gender gender();
		boolean disableEmail();
		
		byte[] profilePicture();
	}
	
	@Output interface Values {
		V<List<DropdownElement>> GENDER_OPTIONS = v();
		V<User> USER = v();
	}
	
	void action(final User user, final Params p, PersistenceManager pm, UserAuthenticator userAuthenticator) {
		final String email = p.email();
		
		final ProfilePictureData profilePicture = ProfilePictureData.getProfilePicture(p.profilePicture());
		
		User u;
		if (email != null || profilePicture != null) {
			// save picture first
			ProfilePicture.saveProfilePicture(user, pm, profilePicture); 
					
			u = new KTrans<User>(pm) {
				@Override protected User call() {
					User u = QueryBuilder.begin(pm, User.class).getSingleByKey(user.getKey());
					if (email != null) {
						User.checkCanSetEmail(pm, u, email);
						
						u.setEmail(email);
						u.setFirstName(Utils.notNull(p.firstName(), "First name is required"));
						u.setLastName(Utils.notNull(p.lastName(), "Last name is required"));
						u.setGender(Utils.notNull(p.gender(), "Gender is required"));
						u.setDisableEmail(p.disableEmail());
					}
					if (profilePicture != null)
						u.setProfilePictureInfo(profilePicture);
					
					pm.makePersistent(u);
					return u;
				}
			}.go();
			userAuthenticator.userUpdated(u);
		} else {
			u = user;
		}
		
		attr(Values.GENDER_OPTIONS, DropdownElement.fromEnum(Gender.class, u.getGender()));
		attr(Values.USER, u);
	}

	@Override public String getPageTitle() { return "Edit profile"; }

}
